package Servlets;

import main.ServerGlobals;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import protocol.HTTPRequest;
import protocol.HTTPResponse;
import protocol.Headers;
import SQL.SQLLiteHandler;

public class Login extends Servlet {

	private boolean isPhoneOrUsernameTaken(String phone, String username) {
		String sql = "select * from " + WhatsAppConstatnts.TABLE_USERS
				+ " where " + WhatsAppConstatnts.USERNAME + "='"
				+ SQLLiteHandler.clean(username) + "' or "
				+ WhatsAppConstatnts.PHONE + "='" + SQLLiteHandler.clean(phone)
				+ "'";
		JSONArray res = fSQLLiteHandler.Query(sql);
		if (res.size() > 0) {
			return true;
		}
		return false;
	}

	@SuppressWarnings("unchecked")
	@Override
	public HTTPResponse process(HTTPRequest httpRequest,
			ServerGlobals serverGlobals) {
		if (!this.isCorrectMethod(httpRequest, Headers.POST)) {
			return new HTTPResponse(Headers.STATUS_405, Headers.HTTP_VERSION,
					new JSONObject(), "", false);
		}

		if (!this.areParametersRequiredSent(new String[] {
				WhatsAppConstatnts.USERNAME, WhatsAppConstatnts.PHONE },
				httpRequest)) {
			return new HTTPResponse(Headers.STATUS_200, Headers.HTTP_VERSION,
					new JSONObject(),
					"ERROR 765: Cannot login, missing parameter", false);
		}

		JSONObject headers = new JSONObject();
		JSONObject UP = httpRequest.getfHttpmsg().toJSONObject();

		String sql = "select * from "
				+ WhatsAppConstatnts.TABLE_USERS
				+ " where "
				+ WhatsAppConstatnts.USERNAME
				+ "='"
				+ SQLLiteHandler.clean((String) UP
						.get(WhatsAppConstatnts.USERNAME))
				+ "' and "
				+ WhatsAppConstatnts.PHONE
				+ "='"
				+ SQLLiteHandler.clean((String) UP
						.get(WhatsAppConstatnts.PHONE)) + "'";
		JSONArray res = fSQLLiteHandler.Query(sql);
		if (res.size() > 0) {
			// create session cookie
			String sessionId = serverGlobals.generateSessionId();
			serverGlobals.getSession(sessionId).put(
					WhatsAppConstatnts.USERNAME,
					(String) UP.get(WhatsAppConstatnts.USERNAME));
			serverGlobals.getSession(sessionId).put(WhatsAppConstatnts.PHONE,
					(String) UP.get(WhatsAppConstatnts.PHONE));
			HTTPResponse httpRes = new HTTPResponse(Headers.STATUS_200,
					Headers.HTTP_VERSION, headers,
					"Welcome "
							+ ((JSONObject) res.get(0))
									.get(WhatsAppConstatnts.USERNAME)
							+ "@"
							+ ((JSONObject) res.get(0))
									.get(WhatsAppConstatnts.PHONE), false);

			httpRes.getfHTTPResponseHeaders().getfCoockies()
					.put(Headers.SESSIONID, sessionId);
			return httpRes;
		} else {

			if (isPhoneOrUsernameTaken(
					(String) UP.get(WhatsAppConstatnts.PHONE),
					(String) UP.get(WhatsAppConstatnts.USERNAME))) {
				return new HTTPResponse(Headers.STATUS_200,
						Headers.HTTP_VERSION, new JSONObject(),
						WhatsAppConstatnts.ERROR_913, false);
			}

			try {
				String sql2 = "INSERT INTO "
						+ WhatsAppConstatnts.TABLE_USERS
						+ " ( "
						+ WhatsAppConstatnts.USERNAME
						+ ","
						+ WhatsAppConstatnts.PHONE
						+ ") VALUES ('"
						+ SQLLiteHandler.clean((String) UP
								.get(WhatsAppConstatnts.USERNAME))
						+ "','"
						+ SQLLiteHandler.clean((String) UP
								.get(WhatsAppConstatnts.PHONE)) + "')";
				fSQLLiteHandler.Query(sql2);
			} catch (RuntimeException e) {
				if (e.getMessage().equals(SQLLiteHandler.SQL_CONCURRENCY)) {
					if (isPhoneOrUsernameTaken(
							(String) UP.get(WhatsAppConstatnts.PHONE),
							(String) UP.get(WhatsAppConstatnts.USERNAME))) {
						return new HTTPResponse(Headers.STATUS_200,
								Headers.HTTP_VERSION, new JSONObject(),
								WhatsAppConstatnts.ERROR_913, false);
					}
				}
			}

			// create session cookie
			String sessionId = serverGlobals.generateSessionId();
			serverGlobals.getSession(sessionId).put(
					WhatsAppConstatnts.USERNAME,
					(String) UP.get(WhatsAppConstatnts.USERNAME));
			serverGlobals.getSession(sessionId).put(WhatsAppConstatnts.PHONE,
					(String) UP.get(WhatsAppConstatnts.PHONE));
			HTTPResponse httpRes = new HTTPResponse(Headers.STATUS_200,
					Headers.HTTP_VERSION, headers,
					"Welcome "
							+ (httpRequest.getfHttpmsg().toJSONObject())
									.get(WhatsAppConstatnts.USERNAME)
							+ "@"
							+ (httpRequest.getfHttpmsg().toJSONObject())
									.get(WhatsAppConstatnts.PHONE), false);

			httpRes.getfHTTPResponseHeaders().getfCoockies()
					.put(Headers.SESSIONID, sessionId);
			return httpRes;
		}
	}

}
//eyJmZmYiOiJoaGhoIn0=